package webTest.myTag.SimpleTag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.SkipPageException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

/**
 * 防盗链
 * Created by IFT8 on 2015/3/18.
 */
public class Reference extends SimpleTagSupport {
    public static String HOST = "http://127.0.0.1:8085";

    @Override
    public void doTag() throws JspException, IOException {
        //JspContext强转到PageContext
        PageContext pageContext = (PageContext) getJspContext();
        //ServletRequest强转到HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        //根据响应头获取访问来源
        String url = request.getHeader("Referer");
        if (url == null||"".equals(url)) {
            //没有来源判断为直接访问本站
            return;
        }
//        //获取协议名称
//        String scheme = request.getScheme() + "://";
        if (url.startsWith(HOST)) {
            return;
        }
        pageContext.getOut().print("<h3>盗链！！！！2秒后跳转至原文</h3>");
        pageContext.getOut().print("原文地址为：");
        //生成原地址
        String initRUL = request.getRequestURL().toString();
        int start = initRUL.indexOf("/", "http://".length());
        initRUL = HOST + initRUL.substring(start);
        pageContext.getOut().print("<a href='" + initRUL + "'>" + initRUL + "</a>");
        HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
        response.setHeader("Refresh", "1;URL=" + initRUL);
        throw new SkipPageException();
    }
}
